package io.github.source.media.bean;

import com.github.catvod.crawler.Spider;
import com.github.catvod.crawler.SpiderDebug;
import com.github.catvod.net.OkHttp;
import com.github.catvod.utils.Json;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.orhanobut.logger.Logger;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.collection.ArrayMap;
import io.github.source.bean.Site;
import io.github.source.config.VodConfig;
import okhttp3.Call;
import okhttp3.Response;

/**
 * @ClassName: MediaPlayProvider
 * @Description: TODO(获取媒体详情)
 * @author: huangrongcai
 * @date: 2024/6/21
 * @Copyright: 黄嵘才（HuangRc)
 */
interface MediaDetailsProvider {
    final String TAG = "Source.Media.Play.Provider.MediaDetailsProvider";

    /**
     * 获取媒体详情。
     *
     * @param query 查询选项。
     * @param bean  媒体对象。
     * @return 包含媒体详情的MediaResult对象，永远不会为null。
     */
    @NonNull
    MediaResult<List<MediaBean>> getMediaDetails(MediaQuery query, MediaBean bean) throws Exception;

    interface Factory {
        MediaDetailsProvider newCall(MediaQuery query);
    }

    public static MediaDetailsProvider create() {
        return new Impl();
    }

    static class Impl implements MediaDetailsProvider {

        /**
         * 详情
         *
         * @param query 查询选项。
         * @param bean  媒体对象。
         * @return 详情
         */
        @NonNull
        @Override
        public MediaResult<List<MediaBean>> getMediaDetails(MediaQuery query, MediaBean bean) {
            Logger.t(TAG).d("MediaQuery query=" + query);
            try {
                String key = query.getSiteKey();
                String id = query.getId();
                Site site = VodConfig.get().getSite(key);
                if (site.getType() == 3) {//爬虫的
                    Spider spider = VodConfig.get().getSpider(site);
                    String detailContent = spider.detailContent(Collections.singletonList(id));
                    VodConfig.get().setRecent(site);

                    return parseMediaJson(site, detailContent);
                } else if (site.isEmpty() && "push_agent".equals(key)) {//推送的
                    MediaBean vod = new MediaBean();
                    vod.setSiteKey(key);
                    vod.setVodId(id);
                    vod.setVodName(id);
                    vod.setVodPic("https://pic.rmb.bdstatic.com/bjh/1d0b02d0f57f0a42201f92caba5107ed.jpeg");
                    List<MediaBean> list = new ArrayList<>();
                    list.add(vod);
                    return MediaResult.success(bean, list);
                } else {
                    ArrayMap<String, String> params = new ArrayMap<>();
                    params.put("ac", site.getType() == 0 ? "videolist" : "detail");
                    params.put("ids", id);
                    String detailContent = call(site, params, true);

                    //将数据读取
                    return parseMediaJson(site, detailContent);

                }
            } catch (Exception e) {
                e.printStackTrace();
                Logger.t(TAG).e("获取数据异常:" + e);
                return MediaResult.error(500).message("获取数据异常:" + e);
            }

        }

        private MediaResult<List<MediaBean>> parseMediaJson(Site site, String response) {
            MediaResult<List<MediaBean>> result = null;
            if (response == null) {
                result = MediaResult.error(406).message("response is null");
                result.raw(response);/*源数据*/
                return result;
            }
            if (response.isEmpty()) {
                result = MediaResult.error(405).message("response is Empty");
                result.raw(response);/*源数据*/
                return result;
            }
            JsonObject object = Json.parse(response).getAsJsonObject();
            result = parseMediaJson(site, object);
            result.raw(response);/*源数据*/
            return result;
        }

        /**
         * @param site   相关源战点信息
         * @param object JsonObject
         * @return
         */
        private MediaResult<List<MediaBean>> parseMediaJson(Site site, JsonObject object) {
            if (object == null) {
                return MediaResult.error(407).message("object is null");
            }
            List<MediaBean> list = new ArrayList<>();
            //获取媒分类内容（）
            for (JsonElement element : Json.safeListElement(object, "list")) {
                MediaBean item = MediaBean.objectFrom(element, site.getKey());
                list.add(item);
            }
            return MediaResult.success(list);
        }

        private String call(Site site, ArrayMap<String, String> params, boolean limit) throws IOException {
            Call call = fetchExt(site, params, limit).length() <= 1000 ? OkHttp.newCall(site.getApi(), site.getHeaders(), params) : OkHttp.newCall(site.getApi(), site.getHeaders(), OkHttp.toBody(params));
            return call.execute().body().string();
        }

        private String fetchExt(Site site, ArrayMap<String, String> params, boolean limit) throws IOException {
            String extend = site.getExt();
            if (extend.startsWith("http")) extend = fetchExt(site);
            if (limit && extend.length() > 1000) extend = extend.substring(0, 1000);
            if (!extend.isEmpty()) params.put("extend", extend);
            return extend;
        }

        private String fetchExt(Site site) throws IOException {
            Response res = OkHttp.newCall(site.getExt(), site.getHeaders()).execute();
            if (res.code() != 200) return "";
            site.setExt(res.body().string());
            return site.getExt();
        }
    }
}
